package com.jxb.jingchen.buletooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author jinxb
 * date     : 2021/8/19
 * desc     :
 */
public class BluetoothUtils {

    public static BluetoothAdapter getBluetoothAdapter() {
        return BluetoothAdapter.getDefaultAdapter();
    }

    /**
     * 判断本设备是否支持蓝牙
     */
    public static boolean bluetoothEnable() {
        return getBluetoothAdapter() != null;
    }

    /**
     * 判断是否开启蓝牙
     */
    public static boolean isBluetoothOpened() {
        return bluetoothEnable() && getBluetoothAdapter().isEnabled();
    }

    /**
     * 直接开启蓝牙
     */
    public static void openBluetooth() {
        if (bluetoothEnable() && !isBluetoothOpened()) {
            getBluetoothAdapter().enable();
        }
    }

    /**
     * 搜索未配对蓝牙设备
     */
    public static void searchUnboundBluetoothDevice() {
        stopSearch();
        BluetoothAdapter.getDefaultAdapter().startDiscovery();
    }

    /**
     * 停止搜索
     */
    public static void stopSearch() {
        if (bluetoothEnable() && getBluetoothAdapter().isDiscovering()) {
            getBluetoothAdapter().cancelDiscovery();
        }
    }


    /**
     * 获取已绑定的设备
     */
    public static List<BluetoothDevice> searchBoundedBluetoothDevice() {
        Set<BluetoothDevice> bondedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
        List<BluetoothDevice> deviceBeans = new ArrayList<>();
        for (BluetoothDevice bondedDevice : bondedDevices) {
            deviceBeans.add(bondedDevice);
        }
        return deviceBeans;
    }

    /**
     * 配对设备
     */
    public static boolean boundDevice(BluetoothDevice deviceBean)  {
        //配对时，取消搜索
        stopSearch();
        //开始配对配对
        return deviceBean.createBond();
    }
}
